package cnhy.salary.service;

import cn.hutool.core.date.DateUtil;
import cnhy.salary.domain.AttendanceRecord;
import cnhy.salary.domain.Employee;
import cnhy.salary.domain.M3callbackRecord;
import cnhy.salary.domain.ProductionLine;
import cnhy.salary.domain.dto.EmployeeDto;
import cnhy.salary.domain.dto.M3HandlerDto;
import com.moredian.oapi.*;
import com.moredian.oapi.model.app.request.GetAppOrgAccessTokenRequest;
import com.moredian.oapi.model.app.request.GetAppTokenRequest;
import com.moredian.oapi.model.app.request.GetOrgAccessTokenRequest;
import com.moredian.oapi.model.app.response.GetAppOrgAccessTokenResponse;
import com.moredian.oapi.model.app.response.GetAppTokenResponse;
import com.moredian.oapi.model.app.response.GetOrgAccessTokenResponse;
import com.moredian.oapi.model.member.request.CreateMemberRequest;
import com.moredian.oapi.model.member.request.DeleteMemberRequest;
import com.moredian.oapi.model.member.response.CreateMemberResponse;
import com.moredian.oapi.model.member.response.DeleteMemberResponse;
import com.moredian.oapi.model.person.request.*;
import com.moredian.oapi.model.person.response.*;
import com.moredian.oapi.profile.*;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysConfigService;
import ling.common.DataUtil;
import ling.common.EQueryService;
import ling.common.domain.Result;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

@Service
@Slf4j
public class M3HandlerSvc extends EQueryService<M3callbackRecord> {

    @Resource
    ISysConfigService sysConfigService;
    String orgId = "1835256576642908160";
    String orgAuthKey = "PbfayfLi822eTApwVww3LYGbC3fAZ1aX";
    String appId = "1835409090923200512";
    String appKey = "SaluXZKJTiwBJPpHZfz8uWfIKrDbxEtn";
    String appToken = null;
    String accessToken = null;
    Date expiresDate = null;

    /*

{
"orgId":"1835256576642908160",
"orgAuthKey":"PbfayfLi822eTApwVww3LYGbC3fAZ1aX",
"appId":"1835409090923200512",
"appKey":"SaluXZKJTiwBJPpHZfz8uWfIKrDbxEtn"
}

     */
    void initAppCfg() {
        var json = sysConfigService.selectConfigByKey("salary.moredian.cfg");
        if(StringUtils.isBlank(json))
        {
            log.error("考勤机sdk配置信息未找到！配置节点名称：salary.moredian.cfg");
            return;
        }
        var map = DataUtil.toObjByJson(json, Map.class);
        orgId = (String) map.get("orgId");
        orgAuthKey = (String) map.get("orgAuthKey");
        appId = (String) map.get("appId");
        appKey = (String) map.get("appKey");
    }
    public String getAppToken() {
        IOpenApiClient client = getClientObj();
        GetAppTokenRequest request = new GetAppTokenRequest();
        request.setAppId(appId);
        request.setAppKey(appKey);
        GetAppTokenResponse response = client.getResponse(request);
        if (Objects.equals(response.getResult(), "0")) {
            appToken = response.getData().getAppToken();
        }

        return appToken;
    }

    public String getAccessToken() {
        if (accessToken == null || new Date().compareTo(expiresDate) >= 0) {
            IOpenApiClient client = getClientObj();
            GetOrgAccessTokenRequest request = new GetOrgAccessTokenRequest();
            request.setOrgAuthKey(orgAuthKey);
            request.setOrgId(orgId);

            GetOrgAccessTokenResponse response = client.getResponse(request);
            if (Objects.equals(response.getResult(), "0")) {
                accessToken = response.getData().getAccessToken();
                expiresDate = DateUtils.addSeconds(new Date(), response.getData().getExpires() - 60);
            }
        }
        return accessToken;

    }

    public String getAppAccessToken() {
        if (accessToken == null || new Date().compareTo(expiresDate) >= 0) {
            initAppCfg();
            IOpenApiClient client = getClientObj();
            GetAppOrgAccessTokenRequest request = new GetAppOrgAccessTokenRequest();
            request.setAppToken(getAppToken());
            request.setOrgId(orgId);
            request.setOrgAuthKey(orgAuthKey);
            GetAppOrgAccessTokenResponse response = client.getResponse(request);
            if (Objects.equals(response.getResult(), "0")) {
                accessToken = response.getData().getAccessToken();
                expiresDate = DateUtils.addSeconds(new Date(), response.getData().getExpires() - 60);
            }
        }
        return accessToken;

    }

    public IOpenApiClient clientObj;

    public IOpenApiClient getClientObj() {
        if (clientObj == null) {
            clientObj = new DefaultOpenApiClient(DefaultProfile.getProfile("https://oapi.moredian.com"));
        }
        return clientObj;
    }

    //新增用户
    public Result createEmpl(Employee employee) {
        //新建（照片），考勤回调--分析
        IOpenApiClient client = getClientObj();
        CreatePersonRequest createPersonRequest = new CreatePersonRequest();
        createPersonRequest.setAccessToken(getAppAccessToken());
        CreatePersonRequest.CreatePersonRequestBody createPersonRequestBody = new CreatePersonRequest.CreatePersonRequestBody();
        createPersonRequestBody.setPersonType(1);
        createPersonRequestBody.setName(employee.getName());
        createPersonRequestBody.setTpId(employee.getJobNum());
        createPersonRequestBody.setVerifyFace(new File("c:/d.png"));
        //       createPersonRequestBody.setMobile(employee.);
//        createPersonRequestBody.setEmail("13667019491@q.com");
        createPersonRequestBody.setJobNum(employee.getJobNum());
        createPersonRequestBody.setSex(employee.getSex());
//        createPersonRequestBody.setBirthday(1606806589000L);
//        createPersonRequestBody.setTelephone("0570-4052111");
//        createPersonRequestBody.setPost("经理");
        //createPersonRequestBody.setCertNo("36062219xxxxxx0710");
        //createPersonRequestBody.setGroupIdList(Arrays.asList(1683611546376208385L, 1683611546376208386L));
        createPersonRequest.setBody(createPersonRequestBody);
        CreatePersonResponse createPersonResponse = client.getResponse(createPersonRequest);
        return Result.restResult(Objects.equals(createPersonResponse.getResult(), "0"), createPersonResponse.getMessage(), createPersonResponse.getData());
    }
    //修改用户


    public Result createMember(Employee employee) {
        IOpenApiClient client = new DefaultOpenApiClient(DefaultProfile.getProfile("https://oapi.moredian.com"));
        CreateMemberRequest createMemberRequest = new CreateMemberRequest();
        createMemberRequest.setAccessToken(getAppAccessToken());
        CreateMemberRequest.CreateMemberRequestBody createMemberRequestBody = new CreateMemberRequest.CreateMemberRequestBody();
        createMemberRequestBody.setMemberName(employee.getName());
        createMemberRequestBody.setTpId(employee.getJobNum());

//        createMemberRequestBody.setShowFace(new File("path of the picture"));
//        createMemberRequestBody.setVerifyFace(new File("path of the picture"));
//        createMemberRequestBody.setMobile("18312345378");
        createMemberRequestBody.setNickName(employee.getName() +"_"+employee.getJobNum());
        createMemberRequestBody.setJobNum(employee.getJobNum());
//        createMemberRequestBody.setSex(1);
//        createMemberRequestBody.setBirthday(1606820038000L);
//        createMemberRequestBody.setEnterTime(1606820038000L);
//        createMemberRequestBody.setEmail("18612xxxx8@139.com");
//        createMemberRequestBody.setTelephone("18312345378");
//        createMemberRequestBody.setPost("测试");
        createMemberRequest.setBody(createMemberRequestBody);
        CreateMemberResponse createMemberResponse = client.getResponse(createMemberRequest);
        return Result.restResult(Objects.equals(createMemberResponse.getResult(), "0"), createMemberResponse.getResult() + ":" + createMemberResponse.getMessage(), createMemberResponse.getData());
    }

    /** 删除考勤成员
     *
     * @param memberId  成员id
     * @return
     */
    public Result<Boolean> deleteMember(long memberId){
        IOpenApiClient client = new DefaultOpenApiClient(DefaultProfile.getProfile("https://oapi.moredian.com"));
        DeleteMemberRequest deleteMemberRequest = new DeleteMemberRequest();
        deleteMemberRequest.setAccessToken(getAppAccessToken());
        DeleteMemberRequest.DeleteMemberRequestBody deleteMemberRequestBody = new DeleteMemberRequest.DeleteMemberRequestBody();
        deleteMemberRequestBody.setMemberId(memberId);
        deleteMemberRequest.setBody(deleteMemberRequestBody);
        DeleteMemberResponse deleteMemberResponse = client.getResponse(deleteMemberRequest);
        return Result.restResult(Objects.equals(deleteMemberResponse.getResult(), "0"), deleteMemberResponse.getResult() + ":" + deleteMemberResponse.getMessage(), deleteMemberResponse.getData());
    }
    /** 考勤状态更新
     *
     * @param m3Record
     */
    public void AttendanceRecordUpdate(M3callbackRecord m3Record) {
        //考勤判断：首次打卡，末次打卡;先查询是否有回调记录，有则更新最后时间:0正常、1迟到、2缺卡
         var emplDto = queryHelper.queryable(EmployeeDto.class).where(p ->
                p.eq(EmployeeDto::getJobNum, m3Record.getTpId()).or()
                    .eq(EmployeeDto::getSign, m3Record.getPersonId()+"")
        ).firstOrNull();
        if(emplDto==null)
            return;
        var userId = emplDto.getUserId();
        var att = queryHelper.entityQuery(AttendanceRecord.class)
                .where(p -> p.userId().eq(userId))
                .where(a -> a.dayDate().rangeClosed(DateUtil.beginOfDay(m3Record.getRecognizeTime()), DateUtil.endOfDay(m3Record.getRecognizeTime())))
                .firstOrNull();
        if (att == null) {
            att = new AttendanceRecord();
            att.setUserId(userId);
            att.setPostId(emplDto.getPost());
            att.setDayDate(m3Record.getRecognizeTime());
            att.setFirstTime(m3Record.getRecognizeTime());
            att.setSource(m3Record.getId() + "");
            //var emplDto = queryHelper.queryable(EmployeeDto.class).where(p -> p.eq(EmployeeDto::getUserId, userId)).firstOrNull();
            att.setUserName(emplDto.getName());
            att.setDeptId(emplDto.getDeptId());
            att.setDeptName(emplDto.getDeptName());
            att.judgeResult(emplDto.getPostWorkStart(), emplDto.getPostWorkEnd());
            queryHelper.entityQuery().insertable(att).executeRows();
            return;
        }
        var date1=att.getFirstTime();
        var date2=att.getLastTime()==null?date1:att.getLastTime();
        if(m3Record.getRecognizeTime().compareTo(att.getFirstTime()) < 0)
        {
            att.setFirstTime(m3Record.getRecognizeTime());
            att.setLastTime(date2);
            att.setSource(m3Record.getId() + "");
            //var emplDto = queryHelper.queryable(EmployeeDto.class).where(p -> p.eq(Employee::getUserId, userId)).firstOrNull();
            att.judgeResult(emplDto.getPostWorkStart(), emplDto.getPostWorkEnd());
            queryHelper.entityQuery().updatable(att).executeRows();
            return;
        }
        if (att.getLastTime() == null || m3Record.getRecognizeTime().compareTo(att.getLastTime()) > 0) {
            att.setLastTime(m3Record.getRecognizeTime());
            att.setSource(m3Record.getId() + "");
            //var emplDto = queryHelper.queryable(EmployeeDto.class).where(p -> p.eq(Employee::getUserId, userId)).firstOrNull();
            att.judgeResult(emplDto.getPostWorkStart(), emplDto.getPostWorkEnd());
            queryHelper.entityQuery().updatable(att).executeRows();
            return;
        }
    }
}
